using UnityEngine;
using UnityEngine.EventSystems;

namespace Jerry.UiFrame
{
    public class UIBase : UIBehaviour
    {
        internal string WinName;
        internal int Priority;
        
        /// <summary>
        /// 打开窗口时，接收外来的参数
        /// </summary>
        protected object[] Param;

        protected override void Awake()
        {
            transform.SetParent(UIConfig.GetCanvas().transform, false);
            var rect = GetComponent<RectTransform>();
            rect.anchoredPosition = Vector2.zero;
            rect.localScale = Vector3.one;
            transform.SetAsLastSibling();
            enabled = false;
        }

        protected override void Start()
        {
            var mask = GetComponent<JImage>();
            if (mask)
            {
                mask.color = UIConfig.UiMaskColor;
            }
            gameObject.name = WinName;
            OnInitData();
        }

        protected override void OnEnable()
        {
            OnOpen();
            base.OnEnable();
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        protected virtual void OnInitData()
        {

        }
        
        /// <summary>
        /// 窗口被打开
        /// </summary>
        protected virtual void OnOpen()
        {
            
        }

        /// <summary>
        /// 窗口被重新激活，首次打开时不会调用
        /// </summary>
        protected virtual void OnReActivate()
        {
            
        }

        /// <summary>
        /// 获取界面子物体的UI组件
        /// </summary>
        /// <param name="childName"></param>
        /// <returns></returns>
        protected IComponent GetChild(string childName)
        {
            return transform.Find(childName).GetComponent<IComponent>();
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        public virtual void CloseWindow()
        {
           UIManager.Instance.CloseWindow(WinName);
        }

        /// <summary>
        /// 销毁界面
        /// </summary>
        internal virtual void DestroyWindow()
        {
            Destroy(gameObject);
        }
        
        internal void ReceiveParams(params object[] param)
        {
            Param = param;
        }

        /// <summary>
        /// 启用Enable事件
        /// </summary>
        internal void EnableComponent()
        {
            enabled = true;
        }

        /// <summary>
        /// 重新激活窗口
        /// </summary>
        internal void ReActivate()
        {
            OnReActivate();
        }
    }
}